import { generateColumns, generateDictData } from '@/utils/plusUtil.js'
import { addMenu, delMenu, getMenu, listMenu, updateMenu } from "@/api/system/menu";

export const useCommonConfig = ()=>{

  // 基础配置
  const { proxy } = getCurrentInstance()
  const primaryKey = 'menuId'
  const moduleName =  '菜单'
  const apiFn = {
    listApiFn: listMenu,
    delApiFn: delMenu,
    apiFnConfig:{
      info: getMenu,
      add: addMenu,
      edit: updateMenu
    }
  }

  // 删除前处理
  const beforeDelFn = (data)=>{
    return Array.isArray(data) ? data.map((item) => item[primaryKey]).join([',']) : data[primaryKey]
  }

  /** 查询菜单下拉树结构 */
  const menuOptions = ref([])
  function getTreeSelect() {
    menuOptions.value = [];
    listMenu().then(response => {
      const menu = { menuId: 0, menuName: "主类目", children: [] };
      menu.children = proxy.handleTree(response.data, "menuId");
      menuOptions.value.push(menu);
    });
  }

  return {
    proxy,
    primaryKey,
    moduleName,
    apiFn,
    beforeDelFn,
    getTreeSelect,
    menuOptions
  }

}


/**
 * 获取列和字典
 * @param isForm
 * @param data  表单数据对象
 */
export const useColumnsDict = (isForm = false, data) => {
  const { proxy } = getCurrentInstance()
  let formData = ref({})
  if (isForm) {
    if (!data || !isRef(data)) {
      console.error('当 isForm 为 true 时，data 必须是一个 ref 对象')
      return
    }
    formData = data
  }

  const dictRawData  = proxy.useDict(...[
    "sys_show_hide", "sys_normal_disable"
  ])

  // 拓展了propInTable，propInForm
  // 定义在这个里面可以对外层进行覆盖(根据是列表还是表单)
  // orderInForm 可以调整在表单里面显示顺序
  const columnsData = [
    {
      label: '菜单名称',
      prop: 'menuName',
      tableColumnProps: {
        align: 'left',
      }
    },
    {
      label: '图标',
      prop: 'icon',
      hideInSearch: true,
      tableColumnProps: {
        align: 'center',
      }
    },
    {
      label: '排序',
      prop: 'orderNum',
      hideInSearch: true,
      tableColumnProps: {
        align: 'center',
      }
    },
    {
      label: '权限标识',
      prop: 'perms',
      hideInSearch: true,
      tableColumnProps: {
        align: 'center',
      }
    },
    {
      label: '组件路径',
      prop: 'component',
      hideInSearch: true,
      tableColumnProps: {
        align: 'center',
      },
    },
    {
      label: '状态',
      prop: 'status',
      valueType: 'select',
      tableColumnProps: {
        align: 'center',
      },
      options:dictRawData.sys_normal_disable
    },
    {
      label: '创建时间',
      prop: 'createTime',
      hideInSearch: true,
      tableColumnProps: {
        align: 'center',
      },
      render:val=>proxy.parseTime(val)
    },
    {
      label: '操作',
      prop: 'action',
      hideInSearch: true,
      width:230,
      tableColumnProps: {
        align: 'center',
      }
    },
  ]
  const columns = ref([])
  columns.value = generateColumns(columnsData, isForm)
  const dictData = computed(()=>generateDictData(dictRawData))
  return {
    dictData,
    columns,
  }
}

